#include "redis.h"
#include "config.h"
#include "conf/redisconf.h"
#include <hiredis/read.h>

Logger::ptr lvqiang = LoggerMgr::GetInstance()->GetLogger("lvqiang");

bool Redis::connect()
{
    RedisConf redisConf = ConfigMgr::GetInstance()->GetConfig<RedisConf>("RedisConf")->GetValue();
    const char* ip = redisConf.GetHost().c_str();
    int port = redisConf.GetPort();
    std::string passwd = redisConf.GetPasswd();
    struct timeval connectTimeOut = redisConf.GetConnectTimevalOut();
    redisContext* conn = redisConnectWithTimeout(ip, port, connectTimeOut);
    if(conn)
    {
        m_context.reset(conn, redisFree);
        if(passwd != "null")
        {
            redisReply* r = (redisReply*)redisCommand(conn, "auth %s", passwd.c_str());
            if(!r)
            {
                LOG_ERROR(lvqiang) << "auth error(" << ip << ":" << port << ")";
                return false;
            }
            if(r->type != REDIS_REPLY_STATUS)
            {
                LOG_ERROR(lvqiang) << "auth reply type error" << r->type << "(" << ip << ":" << port << ")";
                return false;
            }
            if(!r->str)
            {
                LOG_ERROR(lvqiang) << "auth replay str error:NULL" << "(" << ip << ":" << port << ")";
                return false;
            }
            if(strncasecmp(r->str, "OK", 2))
            {
                LOG_ERROR(lvqiang) << "auth error:" << r->str << "(" << ip << ":" << port << ")";
                return false;
            }
        }
    }
    LOG_INFO(lvqiang) << "连接redis成功";
    return true;
}

